﻿using System.Security.Cryptography;
using System.Text;

namespace CoHubServerCore.Security;

public class Rsa
{
    private readonly RSA _rsa = RSA.Create();

    public string PrivateKey
    {
        get => Convert.ToBase64String(_rsa.ExportRSAPrivateKey());

        set => _rsa.ImportRSAPrivateKey(Convert.FromBase64String(value), out _);
    }

    public string PublicKey
    {
        get => Convert.ToBase64String(_rsa.ExportRSAPublicKey());

        set => _rsa.ImportRSAPublicKey(Convert.FromBase64String(value), out _);
    }

    public string Encrypt(string plain)
    {
        return Convert.ToBase64String(_rsa.Encrypt(Encoding.UTF8.GetBytes(plain), RSAEncryptionPadding.Pkcs1));
    }

    public string? Decrypt(string secret)
    {
        try
        {
            return Encoding.UTF8.GetString(_rsa.Decrypt(Convert.FromBase64String(secret), RSAEncryptionPadding.Pkcs1));
        }
        catch (CryptographicException)
        {
            return null;
        }
    }
}